package com.wang.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wang.decagency.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class TokenUtil {

    /**
     * 生成token
     *
     * @param user
     * @return
     */
    public String generToken(SysUser user) {
        // 创建一个JWT
        Algorithm algorithm = Algorithm.HMAC256("secret");
        String token = JWT.create()
                .withIssuer("auth0")
                .withClaim("userName", user.getUserName())
                .withExpiresAt(new Date(System.currentTimeMillis() + 6 * 60 * 60 * 1000)) // 设置过期时间
                .sign(algorithm);
        log.info("generToken,token:" + token);
        return token;
    }

    public String authToken(String token) {
        if (token == null) {
            return null;
        }
        String userName = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret"); // 使用相同的算法和密钥
            JWTVerifier verifier = JWT.require(algorithm).withIssuer("auth0").build(); // 创建验证器
            DecodedJWT jwt = verifier.verify(token); // 验证token并解码
            userName = jwt.getClaim("userName").asString(); // 获取自定义声明

        } catch (JWTVerificationException exception) {
            log.info("authToken fail");
        }
        log.info("authToken,userName:" + userName);
        return userName;
    }


}
